package com.ccys.netty.handler;

import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author cloud fly
 * @description 描述
 * @date 2024/3/1
 */
@Slf4j
public class AbsHttpJsonDecoder<T> extends MessageToMessageDecoder<T> {
    private final static String CHARSET_NAME = "UTF-8";
    private static Charset UTF_8 = Charset.forName(CHARSET_NAME);
    private Class<?> clazz;

    protected AbsHttpJsonDecoder(Class<?> clazz) {
        this.clazz = clazz;
    }

    protected Object decode(ChannelHandlerContext cxt, ByteBuf body) throws Exception {
        String content = body.toString(UTF_8);
        log.info("content:  ", content);
        Object result =  null;
        try {
            result = new Gson().fromJson(content, clazz);
            log.info("Decode", content);
        } catch (Exception e) {
            log.info("Decode", e.getMessage());
            throw e;
        }

        return result;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, T t, List<Object> list) throws Exception {

    }
}
